package pers.lan.th.java.waitnotify;

import java.util.Random;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/11/28 4:49 PM
 */
public class WaitNotify {

    public static void main(String[] args) {
        final Rep rep = new Rep();
        new Thread(new Mt(rep, false)).start();
        new Thread(new Mt(rep, true)).start();
        new Thread(new Mt(rep, false)).start();
        new Thread(new Mt(rep, true)).start();
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        rep.consume(1);
                        System.out.println("我消费1个");
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    static class Rep {

        int num = MIN;

        private static final int MAX = 10;

        private static final int MIN = 1;

        public void produce(int n) throws InterruptedException {
            synchronized (this) {
                while (num + n > MAX) {
                    this.wait();
                }
                num += n;
                System.out.println("生产\t" + n + "\t剩余\t" + num);

                this.notifyAll();
            }
        }

        public void consume(int n) throws InterruptedException {
            synchronized (this) {
                while (num - n < MIN) {
                    this.wait();
                }
                num -= n;
                System.out.println("消费\t" + n + "\t剩余\t" + num);
                this.notifyAll();
            }
        }
    }


    static class Mt implements Runnable {
        Rep rep;
        boolean c;

        public Mt(Rep rep, boolean c) {
            this.rep = rep;
            this.c = c;
        }

        public void run() {
            Random random = new Random();
            while (true) {
                try {
                    int i = random.nextInt(Rep.MAX - 1) + 1;
                    System.out.println(Thread.currentThread().getId() + "\t" + i);
                    if (c) {
                        rep.consume(i);
                    } else {
                        rep.produce(i);
                    }
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
